package com.lfl.controller;

import com.lfl.pojo.Result;
import com.lfl.pojo.User;
import com.lfl.service.UserService;
import com.lfl.utils.JwtUtil;
import com.lfl.utils.Md5Util;
import com.lfl.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^[a-zA-Z0-9_]{5,16}$") String username, @Pattern(regexp = "^[a-zA-Z0-9_]{6,16}$") String password) {
        //TODO 查询用户是否存在 如果不存在，则创建用户
        User u = userService.findByUserName(username);
        if (u == null) {
            //没有就需要创建用户
            userService.register(username, password);
            return Result.success();
        } else {
            //如果存在，则返回错误信息
            return Result.error("用户名已存在");
        }

    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^[a-zA-Z0-9_]{5,16}$") String username, @Pattern(regexp = "^[a-zA-Z0-9_]{6,16}$") String password) {

        //TODO 根据用户名查询User
        User loginUser = userService.findByUserName(username);
        //TODO 判断是否查询到

        if (loginUser == null) {
            return Result.error("用户名不存在或者错误");
        }
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            //登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);

            //TODO 保存token到Redis
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            ops.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }

        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(@RequestHeader(name = "Authorization") String token) {
        //TODO 根据token获取用户信息
//        Map<String, Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }


    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updataPwd(@RequestBody Map<String, String> params,@RequestHeader("Authorization") String token) {
        //TODO 校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        //TODO 校验这三个密码是否为空
        if (    !StringUtils.hasLength(oldPwd) ||
                !StringUtils.hasLength(newPwd) ||
                !StringUtils.hasLength(rePwd)
        ) {
            return Result.error("参数不能为空");
        }

        //TODO 校验原密码是否正确
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码错误");
        }
        //TODO 校验新密码和确认密码是否一致
        if (!newPwd.equals(rePwd)) {
            return Result.error("两次填写新密码不一致");
        }

        //TODO 密码更新
        userService.updatePwd(newPwd);

        //TODO 清除Redis中的token
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        RedisOperations<String, String> operations = ops.getOperations();
        operations.delete(token);


        return Result.success();
    }
}


